<?php

namespace app\admin\controller\hongruan;

use app\common\controller\Backend;
use app\common\model\HrCode;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 虹软激活码
 *
 * @icon fa fa-table
 * @remark
 */
class Codes extends Backend
{
    /**
     * @var HrCode
     */
    protected $model = null;
    protected $noNeedRight = ['notActivate', 'activate', 'download', 'import', 'distribute'];

    protected $schoolLimit = true;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model("HrCode");
    }

    /**
     * 查看
     */
    public function index()
    {
        return $this->view->fetch();
    }

    // 未分配
    public function unallocated()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('admin_id', 0)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('admin_id', 0)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

    // 已分配
    public function allocated()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('admin_id', '>', 0)
                ->group('admin_id')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('admin')
                ->where($where)
                ->where('admin_id', '>', 0)
                ->field('admin_id id,admin_id,count(*) count,SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) used_count')
                ->order($sort, $order)
                ->group('admin_id')
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function detail($ids = 0)
    {
        $data = HrCode::where('admin_id', $ids)
            ->field('SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) notActivate,SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) activate')
            ->find();
        $this->assign('data', $data);
        $this->assignconfig('admin', ['ids' => $ids]);
        return $this->view->fetch();
    }

    // 未激活
    public function notActivate($ids = 0)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('admin_id', $ids)
                ->where('status', HrCode::NOT_ACTIVATE)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('admin_id', $ids)
                ->where('status', HrCode::NOT_ACTIVATE)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

    // 已激活
    public function activate($ids = 0)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('admin_id', $ids)
                ->where('status', HrCode::ACTIVATE)
                ->order($sort, $order)
                ->count();

            $list = $this->model->with('school')
                ->where($where)
                ->where('admin_id', $ids)
                ->where('status', HrCode::ACTIVATE)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }



    /**
     * 下载模板
     */
    public function download()
    {
        $file_path = 'template/虹软激活码.xlsx';
        $file_dir = ROOT_PATH . 'public' . DS . 'uploads' . DS . "$file_path";    // 下载文件存放目录

        // 检查文件是否存在
        if (!file_exists($file_dir)) {
            $this->error('文件不存在');
        } else {
            // 打开文件
            $file1 = fopen($file_dir, "r");
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:" . filesize($file_dir));
            Header("Content-Disposition: attachment;filename=虹软激活码.xlsx");
            ob_clean();     // 重点！！！
            flush();        // 重点！！！！可以清除文件中多余的路径名以及解决乱码的问题：
            //输出文件内容
            //读取文件内容并直接输出到浏览器
            echo fread($file1, filesize($file_dir));
            fclose($file1);
            exit();
        }
    }

    /**
     * 批量导入
     *
     * @return string|void
     * @throws Exception
     * @throws PDOException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\DbException
     */
    public function import()
    {
        if ($this->request->isAjax()) {

            set_time_limit(0);
            ini_set('memory_limit', '512M');
            $file = $this->request->request('file');

            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
            $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {
                if ($importHeadType == 'comment') {
                    $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                } else {
                    $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
                }
            }

            //加载文件
            $insert = [];

            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];
                for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = $val;
                    }
                }

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];
                    $temp = array_combine($fields, $values);

                    foreach ($temp as $k => $v) {
                        if ($k !== '' && isset($fieldArr[$k])) {
                            $row[$fieldArr[$k]] = $v;
                        }
                    }

                    if ($row) {
                        $insert[] = $row;
                    }
                }

            } catch (Exception $exception) {
                $this->error($exception->getMessage() ? $exception->getMessage() : '添加失败');
            }

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }

            $limit = 500;
            $count = ceil(count($insert) / $limit);
            for ($i = 1; $i <= $count; $i++) {
                $offset = ($i - 1) * $limit;
                $data = array_slice($insert, $offset, $limit);

                // 启动事务
                Db::startTrans();
                try {

                    $this->model->saveAll($data);

                    // 提交事务
                    Db::commit();
                } catch (PDOException $exception) {

                    // 回滚事务
                    Db::rollback();

                    $msg = $exception->getMessage();
                    if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                        $msg = "导入失败，激活码【{$matches[1]}】已存在";
                    };

                    $this->error($msg ? $msg : '导入失败');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage() ? $e->getMessage() : __('导入失败'));
                }
            }

            $this->success();
        }

        return $this->view->fetch();

    }

    /**
     * 批量分配
     *
     * @User ZhenZiHan
     * @Date 2020/2/25
     *
     */
    public function distribute($ids = 0)
    {
        if ($this->request->isAjax()) {

            $params = $this->request->post("row/a");

            if ($params) {

                if ($ids) {
                    $hr_codes = HrCode::where('id', $ids)
                        ->where('status', HrCode::NOT_ACTIVATE)
                        ->where('admin_id', 0)
                        ->find();
                    if (!$hr_codes) {
                        $this->error('激活码不存在');
                    }

                    $hr_codes->update(['admin_id' => $params['admin_id']]);

                    $this->success();

                } else {
                    if ($params['count'] > 0 ) {

                        $hr_codes = HrCode::where('status', HrCode::NOT_ACTIVATE)->where('admin_id', 0)->limit($params['count'])->select();

                        if (count($hr_codes) < $params['count']) {
                            $this->error('激活码库存不足');
                        }

                        $code_ids = array_column($hr_codes, 'id');

                        HrCode::whereIn('id', $code_ids)
                            ->where('status', HrCode::NOT_ACTIVATE)
                            ->where('admin_id', 0)
                            ->update(['admin_id' => $params['admin_id']]);

                        $this->success();

                    } else {
                        $this->error('数量必须大于0');
                    }

                }


            }

            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->assign('ids', $ids);
        return $this->view->fetch();
    }
}
